/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.JOptionPane;

/**
 *
 * @author USER
 */
public class MySqlDataAccessHelper {

    private Connection connection;

    public void open() {

        try {

            DriverManager.registerDriver((new org.gjt.mm.mysql.Driver()));
            String url = "jdbc:mysql://localhost:3306/bookonlinev3";
            Properties info = new Properties();
            info.setProperty("user", "root");
            info.setProperty("password", "root");
            info.setProperty("characterEncoding", "UTF-8");
            connection = DriverManager.getConnection(url, info);

        } catch (Exception w) {
        }
    }

    public void close() {
        try {
            this.connection.close();
        } catch (Exception e) {
        }
    }

    public ResultSet executeQuery(String sql) {
        ResultSet rs = null;

        try {
            Statement sm = this.connection.createStatement();
            rs = sm.executeQuery(sql);
        } catch (Exception e) {
        }

        return rs;
    }

    public boolean executeNonQuery(String sql) {
        boolean kq = false;
        try {
            Statement sm = this.connection.createStatement();
            int n = sm.executeUpdate(sql);
            if (n == 1) {
                kq = true;
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());

        }

        return kq;
    }

    public int executeNonQueryReturnGeneratedKey(String sql) {
        int ma = 0;
        try {
            Statement sm = this.connection.createStatement();
            int n = sm.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = sm.getGeneratedKeys();
            if (rs.next()) {
                ma = rs.getInt(1);
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());

        }

        return ma;
    }
}
